import { Component, OnInit , OnDestroy} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {ChangeDetectionStrategy} from '@angular/core';
import {Store} from '@ngrx/store';
import * as fromRoot from '../../reducers';
import * as authActions from '../../actions/auth.action';
import {equalValidator} from '../../validators/validators';
import { debounceTime, filter } from 'rxjs/operators';
import {isValidDate} from '../../utils/date.util';
import {extractInfo , isValidAddr, getAddrByCode} from '../../utils/identity.util';
import { Subscription } from 'rxjs';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterComponent implements OnInit ,OnDestroy{
  items: string[];
  form: FormGroup;
  sub: Subscription;
  private readonly avatarName ='people';
  constructor(private fb:FormBuilder,private store$:Store<fromRoot.State>) { }

  ngOnInit() {
    const nums = this.getNum(16);
    const img = `${this.avatarName}${Math.floor(Math.random()*16+1)}`
    this.items = nums.map((d)=>`people${d}`)
    this.form = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', Validators.required],
      passwordGroup: this.fb.group({
        password: ['', Validators.minLength(6)],
        pconfirm: ['']
      }, {validator: equalValidator}),
      avatar: [img],
      dateOfBirth: ['1990-01-01'],
      address: [],
      identity: []
    });
    const id$ = this.form.get('identity').valueChanges.pipe(
      debounceTime(300),
      filter(_ => this.form.get('identity').valid)
    );
    this.sub = id$.subscribe(id => {
      const info = extractInfo(id.identityNo);
      if (isValidAddr(info.addrCode)) {
        const addr = getAddrByCode(info.addrCode);
        this.form.get('address').patchValue(addr);
      }
      if ( isValidDate(info.dateOfBirth)) {
        this.form.get('dateOfBirth').patchValue(info.dateOfBirth);
      }
    });
  }
  ngOnDestroy() {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }
  getNum(num) {
    const arr = [];
    for (let i = 1; i <= num; i++) {
      arr.push(i);
    }
    return arr;
  }
  onSubmit({value, valid}, ev: Event) {
     ev.preventDefault();
     if (!valid) {
       return;
     }
     const submitValue = {...value, password: value['passwordGroup']['password'], pconfirm: value['passwordGroup']['pconfirm']};
     delete submitValue['passwordGroup'];
     this.store$.dispatch(new authActions.RegisterAction(submitValue));
  }
}
